<script setup>
	import {
		ref,
		computed,
		reactive,
		onMounted
	} from 'vue';
	import {
		base64ToPath,
		pathToBase64
	} from '@/static/libs/image-tools.js';
	import html2canvas from "/components/html2canvas/html2canvas.vue"
	import {
		onLoad,
		onShow,
		onReady,
		onHide,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		wdfxStr,
		imgSrc
	} from "./resource.js";
	import {
		LPAPIFactory,
		LPA_Result,
		LPAUtils
	} from '@/uni_modules/dothan-lpapi-ble/js_sdk/index.js';
	const domId = ref('')
	onMounted(() => {})
	const lpapi = ref(null);
	const props = defineProps({});
	const platform = ref({});
	const startSearchBlueDevices = () => {
		uni.openBluetoothAdapter({
			success(res) {
				uni.showLoading({
					title: "正在搜索打印机建议开启GPS...",
				});
				// 搜索蓝牙设备
				lpapi.value.startBleDiscovery({
					timeout: 5000,
					deviceFound: (devices) => {
						uni.hideLoading()
						onDeviceFound(devices);
					},
					adapterStateChange: (result) => {
						if (!result.discovering) {
							uni.hideLoading();
						}
					},
				});
			},
			fail(err) {
				uni.showToast({
					title: '请打开蓝牙和GPS定位',
					icon: 'none'
				});
				return false;
			}
		});
	};
	const context = ref(null)
	onReady(() => {
		context.value = lpapi.value.createDrawContext({
			canvas: undefined,
			canvasId: canvasId,
		});
		lpapi.value.setDrawContext(context.value);
	})
	onHide(() => {
		uni.hideLoading()
	})
	onUnload(() => {
		uni.hideLoading()
	})
	onLoad(() => {
		lpapi.value = LPAPIFactory.getInstance({
			isDingTalk: false
		});
		startSearchBlueDevices();
		uni.onBLEConnectionStateChange((res) => {
			if (!res.connected) {
				lianjiel.value = false
			}
		})
	});
	const deviceList = ref([]);

	function onDeviceFound(devices) {
		if (devices && devices.length > 0) {
			deviceList.value.splice(0);
			for (let item of devices) {
				deviceList.value.push(item);
				const advertisData = item.advertisData ? new Uint8Array(item.advertisData) : undefined;
				const advDataStr = advertisData ? LPAUtils.getHexStringOfBytes(advertisData) : '-';
				console.log(`---- advertisData [${item.name}] : [${advDataStr}]`);
			}
		}
	}
	const type = ref(2);
	onShow(async () => {
		platform.value = uni.getStorageSync('platform');
	});
	// 开始处理逻辑了
	const list = ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 123, 34, 4234, 24, 234, 234, 23543, 36, 546, 4365, 346, 5234,
		6234, 523,
		5, 325, 3, 53, 5, 325, 3, 543, 5, 35
	]);
	const goback = () => {
		uni.navigateBack()
	}
	const submit = async () => {
		if (!lianjiel.value) {
			uni.showToast({
				title: '请先连接打印设备',
				icon: 'none'
			});
			return;
		}
		if (list.value.length < 1) {
			uni.showToast({
				title: '请添加要打印的单词',
				icon: 'none'
			});
			return;
		}
		domId.value = '#poster'
		setTimeout(() => {
			base64PrintTest()
		}, 300)
	};
	const change = (index) => {
		if (index == 0) {
			startSearchBlueDevices();
		} else {
			plus.runtime.launchApplication({
					action: 'android.settings.BLUETOOTH_SETTINGS'
				},
				(e) => {
					uni.showToast({
						title: '跳转失败：' + e.message,
						icon: 'none'
					});
				}
			);
		}
	};
	const isAlipay = ref(false);
	const deviceIndex = ref(0)
	const getDevice = () => {
		return deviceList.value[deviceIndex.value];
	}
	const lianjieBlue = (index) => {
		deviceIndex.value = index
		openPrinter()
	}
	const lianjiel = ref(false)
	// 开始链接了
	const openPrinter = (callback) => {
		const currDevice = getDevice();
		if (currDevice && currDevice.deviceId) {
			uni.showLoading({
				title: "正在链接打印机...",
			});
			lpapi.value.openPrinter({
				name: currDevice.name,
				deviceId: currDevice.deviceId,
				tryTimes: isAlipay.value ? 1 : 5,
				success: (resp) => {
					lianjiel.value = true
					console.log(`---- 【打印机链接成功】`);
					console.log(resp.resultInfo);
					uni.hideLoading();
					uni.showToast({
						title: "打印机链接成功",
						icon: "icon"
					});
					if (typeof callback === "function") {
						callback(true);
					}
				},
				fail: (resp) => {
					console.warn(`---- 【打印机链接失败】：`);
					console.warn(JSON.stringify(resp));
					uni.hideLoading();
					uni.showToast({
						title: "打印机链接失败重试中！",
						icon: "none"
					});
					if (typeof callback === "function") {
						callback(false);
					}
				},
			});
		} else {
			console.warn("---- 未检测到打印机！");
			uni.showToast({
				title: "未检测到打印机",
				icon: "none",
				duration: 1500
			});
			if (typeof callback === "function") {
				callback(false);
			}
		}
	};
	const canvasId = "lpapi-ble-uni1"
	const labelWidth = 960
	const labelHeight = 960


	const files = ref('')
	// 生成的图片
	const renderFinish = (file) => {
		files.value = file
	}
	const html2canvass = ref(null)
	const dpi = 300;
	const screenWidth = 750;
	const rpxToPx = (rpx) => rpx * (screenWidth / 750);
	const pxToMm = (px) => px * (25.4 / dpi);
	let widthInRpx = 566;
	let heightInRpx = 105 * list.value.length + 40;
	let widthInPx = rpxToPx(widthInRpx);
	let heightInPx = rpxToPx(heightInRpx);
	let widthInMm = pxToMm(widthInPx);
	let heightInMm = pxToMm(heightInPx);

	function base64PrintTest() {
		const currDevice = getDevice();
		console.log(1111);
		console.log({
			printerName: currDevice.name,
			width: widthInMm,
			height: heightInRpx,
			image: files.value,
		});
		if (currDevice) {
			lpapi.value
				.printImage({
					printerName: currDevice.name,
					width: 80,
					height: 400,
					image: files.value,
				})
				.then((resp) => {
					if (resp.statusCode === 0) {
						console.log(`---- BASE64 图片打印成功！`);
					} else {
						console.warn(`---- BASE64 图片打印失败，statusCode= ${resp.statusCode}`);
						console.warn(resp);
					}
				});
		}
	}
</script>

<template>
	<canvas :id="canvasId" :canvas-id="canvasId" type="2d" :style="{ width: 760 + 'px', height: 3000 + 'px' }"
		style="position: fixed; left: -999999rpx; top: -999999rpx" />
	<view class="wrap">
		<view class="header-wrap uni-row" :style="{
                paddingTop: platform.dingbu + 'rpx',
                height: platform.dingbu + 96 + 'rpx'
            }">
			<image class="left" src="/static/img/goback-black.png" @click="goback" mode="widthFix" />
			<view class="title"> 打印 </view>
			<view class="right-text"> 15个单词 </view>
		</view>
		<scroll-view scroll-y="true" :style="{
                height:platform.gaodu- platform.dingbu - 96 + 'rpx'
            }">
			<view class="label"> 1、打开蓝牙，并关联上打印机 </view>
			<view class="label"> 2、点击打印后请等待3秒左右，等待打印完成即可 </view>
			<view class="cen-top uni-row" style="opacity: 0;">
				<text class="xinde">打印状态:</text>
				<text class="cu"></text>
			</view>
			<view class="list " v-if="!lianjiel">
				<view class="item uni-row" v-for="(item,index) in deviceList" :key="index">
					<view class="left">
						打印机设备名称: {{item.name}}
					</view>
					<view class="right uni-row" @click="lianjieBlue(index)">
						连接
					</view>
				</view>
			</view>

			<view class="caozuo uni-row">
				<view class="item uni-row" v-for="(item, index) in ['搜索打印机', '蓝牙']" :key="index" @click="change(index)">
					{{ item }}
				</view>
			</view>
			<view class="dayin-status uni-row">
				<view class="left uni-row">
					<view class="item uni-row" v-for="(item, index) in ['只打中文', '只打英文', '全部打印']" :key="index"
						:class="index == type ? 'active' : 'default'" @click="type = index">
						{{ item }}
					</view>
				</view>
				<view class="right"> 序列号：待查询 </view>
			</view>
			<scroll-view scroll-y="true" :style="{
	        height: platform.gaodu - platform.dingbu - 92 - 72 - 52 - 116 - 128-80 + 'rpx'
	    }" class="src">
				<html2canvas ref="html2canvass" :domId="domId" @renderFinish="renderFinish">
					<view id="poster" class="list uni-col">
						<view class="item uni-row" v-for="(item, index) in list" :key="index">
							<view class="left" :style="{ opacity: type == 1 ? 0 : 1 }"> {{item}} </view>
							<view class="" style="height: 85rpx; width: 1rpx; background-color: #979797" />
							<view class="code" :style="{ opacity: type == 0 ? 0 : 1 }"> index </view>
						</view>
						<view class="" style="height: 130rpx;" />
					</view>
				</html2canvas>
			</scroll-view>
		</scroll-view>
	</view>
	<view class="btnss uni-row" @click="submit"> 提交打印 </view>
</template>

<style scoped lang="less">
	.wrap {
		background-color: #f8f3ff;
		height: 100%;

		.header-wrap {
			justify-content: space-between;
			padding-left: 24rpx;
			padding-right: 24rpx;

			.left {
				width: 48rpx;
				margin-right: 94rpx;
			}

			.title {
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;
			}

			.right-text {
				width: 142rpx;
				font-size: 28rpx;
				color: #333333;
			}
		}

		.label {
			padding: 6rpx 29rpx;
			font-size: 24rpx;
			color: #666666;
		}

		.cen-top {
			justify-content: center;
			margin: 10rpx 0;

			.xinde {
				font-size: 24rpx;
				color: #666;
			}

			.cu {
				font-size: 32rpx;
				color: #6489fa;
			}
		}

		.list {
			justify-content: space-between;
			padding: 0 28rpx;
			font-size: 28rpx;

			.item {
				justify-content: space-between;
				margin: 10rpx;

				.right {
					justify-content: center;
					width: 170rpx;
					height: 56rpx;
					background: #9561f3;
					border-radius: 8rpx;
					font-size: 28rpx;
					color: #ffffff;
				}
			}
		}

		.caozuo {
			justify-content: space-around;
			padding: 0 180rpx;
			margin: 20rpx 0 40rpx;

			.item {
				justify-content: center;
				width: 170rpx;
				height: 56rpx;
				background: #9561f3;
				border-radius: 8rpx;
				font-size: 28rpx;
				margin-bottom: 10rpx;
				color: #ffffff;
			}
		}

		.dayin-status {
			padding: 0 28rpx;
			height: 108rpx;
			background-color: #f3eaff;
			justify-content: space-between;

			.left {
				justify-content: space-between;

				.item {
					justify-content: center;
					width: 156rpx;
					height: 72rpx;
					border-radius: 8rpx;
					font-size: 28rpx;
					margin-right: 20rpx;

					&:last-child {
						margin-right: 0;
					}

					&.default {
						color: #999999;
						border: 2rpx solid #999999;
					}

					&.active {
						background: #fa6f01;
						color: #fff;
					}
				}
			}

			.right {
				flex-shrink: 0;
				font-size: 20rpx;
				color: #999999;
			}
		}

		.src {
			background-color: #f8f3ff;

			.list {
				padding: 20rpx 0;
				align-items: center;

				.item {
					width: 566rpx;
					border-top: 1rpx solid #979797;
					border-bottom: 1rpx solid #979797;
					transition: 0.3s all;

					.left,
					.code {
						flex: 1;
						height: 85rpx;
						line-height: 85rpx;
						text-align: center;
					}
				}
			}
		}
	}

	.btnss {
		position: fixed;
		left: 50%;
		bottom: 30rpx;
		transform: translate(-50%, 0);
		justify-content: center;
		width: 610rpx;
		height: 88rpx;
		background: #9561f3;
		border-radius: 16rpx;
		font-size: 32rpx;
		color: #ffffff;
	}
</style>